package cn.zch.soft.util.process.host;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import sun.jvmstat.monitor.*;

import java.net.URISyntaxException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
/**
 * @author zchcpywin10
 */
@Slf4j
public class NamedHostProcesses {
  public static void main(String[] args) {
    try {
      // 获取监控主机
      MonitoredHost local = MonitoredHost.getMonitoredHost("localhost");
      // 取得所有在活动的虚拟机集合
      Set<Object> vmList = Collections.unmodifiableSet(new HashSet<Object>(local.activeVms()));
      log.info("vmList:{}", vmList);
      // 遍历集合，输出PID和进程名
      for (Object process : vmList) {
        MonitoredVm vm = local.getMonitoredVm(new VmIdentifier("//" + process));
        log.info("vm{}", vm);
        log.info("vm{}", JSON.toJSONString(vm));
        // 获取类名
        String processName = MonitoredVmUtil.mainClass(vm, true);
        log.info(process + " ------> " + processName);
      }
      Thread.sleep(30000);
    }
    catch (InterruptedException | MonitorException | URISyntaxException e) {
      log.error(e.getMessage());
      Thread.currentThread().interrupt();
    }
  }
}
